from django.http import HttpResponse
from django.utils import simplejson, html
import seeker
import math

def render( request, plugin, search, result, page=0, page_size=-1 ):
	num_rows = result.count()
	if page_size < 0:
		page = 0
		page_size = num_rows
	offset = page * page_size
	page_count = int( math.ceil( float(num_rows) / float(page_size) ) )
	
	# Get a list of all possible display fields.
	display_fields = []
	for (name,fields) in plugin.get_display_fields( request ):
		display_fields.extend( fields )
	
	# Build a dictionary of which fields are lookups, to avoid checking with the
	# plugin each time during the nested loop below.
	is_lookup = {}
	for field in display_fields:
		is_lookup[field] = False
		if plugin.get_field_type(request,field) == seeker.TYPE_LOOKUP:
			is_lookup[field] = True
	
	rows = []
	for k in range(page_size):
		if (k + offset) >= num_rows:
			continue
		data = {}
		for field in display_fields:
			# Return formatted and unformatted values for all possible display fields, so
			# that the search interface can avoid round trips for hiding/showing columns.
			vals = [ html.escape(result.get_html(k+offset,field,False)) ]
			if is_lookup[field]:
				vals.append( html.escape(result.get_html(k+offset,field,True)) )
			data[field] = vals
		rows.append( data )
	
	params = {
		'count': num_rows,
		'pages': page_count,
		'page': page + 1,
		'start': offset + 1,
		'end': offset + len(rows),
		'rows': rows,
		'has_next': ((page + 1) < page_count),
		'has_prev': (page > 0),
	}
	
	return HttpResponse( simplejson.dumps(params), mimetype='application/json' )
